import React, { Fragment, useEffect, useState } from 'react';
import { ColumnProps, PaginationConfig, SorterResult } from 'antd/es/table';
import moment from "moment";
import { Divider, Card, Table, message, Button, Tag, Popconfirm, Modal, Switch } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from '@/utils/table.less';
import { connect } from 'dva';
import apis from '@/services';
import { WorkorderItem } from '@/pages/device/workorder/data';
import { ConnectState, Dispatch } from '@/models/connect';
import encodeQueryParam from '@/utils/encodeParam';
import Save from './save';
import SearchForm from '@/components/SearchForm';
import { VirtualAction } from 'rxjs';
import { times } from 'lodash';

interface Props {
  workorder: any;
  dispatch: Dispatch;
  location: Location;
  loading: boolean;
}

interface State {
  data: any;
  instanceList: any;
  orderList: any;
  stateList: any;
  sendOrderList: any;
  searchParam: any;
  saveVisible: boolean;
  modelVisible: boolean;
  issue: boolean;
  current: Partial<WorkorderItem>;
  count: number;
  interval: any;
  pageSize: number;
  pageIndex: number;
}

const WorkorderList: React.FC<Props> = props => {
  const { dispatch, location } = props;

  const { result } = props.workorder;
  const initState: State = {
    data: result,
    searchParam: { pageSize: 10,pageIndex: 0, terms: location?.query?.terms, },
    pageSize: 10,
    pageIndex: 0,
    saveVisible: false,
    modelVisible: false,
    issue: false,
    current: {},
    instanceList: [],
    sendOrderList: [],
    orderList: [],
    count: 0,
    interval: [],
    stateList: [
      {
        id: '0',
        name : '待下发'
      },
      {
        id: '1',
        name : '已下发'
      },
      {
        id: '2',
        name : '执行中'
      },
      {
        id: '3',
        name : '已完成'
      },
      {
        id: '4',
        name : '取消'
      },
    ]
  };

  const [searchParam, setSearchParam] = useState(initState.searchParam);
  const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
  const [issue, setIssue] = useState(initState.issue);
  const [modelVisible, setModelVisible] = useState(initState.modelVisible);
  const [instanceList, setInstanceList] = useState(initState.instanceList);
  const [orderList, setOrderList] = useState(initState.orderList);
  const [stateList, setStateList] = useState(initState.stateList);
  const [sendOrderList, setSendOrderList] = useState(initState.sendOrderList);
  const [current, setCurrent] = useState(initState.current);
  const [count, setCount] = useState(initState.count);
  const [interval, setInterval] = useState(initState.interval);
  const [pageIndex, setPageIndex] = useState(initState.pageIndex);
  const [pageSize, setPageSize] = useState(initState.interval);

  const handleSearch = (param?: any) => {
    console.log('orderList',orderList,orderList.length)
    dispatch({
      type: 'workorder/query',
      payload: encodeQueryParam(param),
    });
    // apis.workorder.list
  };

  const edit = (record: WorkorderItem) => {
    setCurrent(record);
    setSaveVisible(true);
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any) => {
      console.log(selectedRowKeys)
      setCount(selectedRowKeys.length)
      setOrderList(selectedRowKeys);
    },
  };
  // 是否选择默认100组工单下发弹窗显示
  const showModal = (record: any[]) => {
    setModelVisible(true);
    setSendOrderList(record)
  };
  // 弹窗确认
  const handleOk = () => {
    sendOrder()
  };
  // 弹窗取消
  const handleCancel = () => {
    setModelVisible(false);
    setSendOrderList([])
  };
  
  // 是否选择默认100组工单下发选择
  const onChangeSwitch = (value: boolean) =>{
    setIssue(value)
  }
 //下发
 const sendOrder = () => {
    if(!sendOrderList.length){ 
      message.error("请选择工单进行下发操作");
      return
    }
    var params = {
      sendOrderList: sendOrderList,
      issue: issue
    }
    dispatch({
      type: 'workorder/sendOrder',
      payload: params,
      callback: (response: any) => {
        if (response.status === 200) {
          setModelVisible(false);
          message.success('操作成功');
          setIssue(false)
          orderList.splice(0, orderList.length);
          setOrderList([])
          handleSearch(searchParam);
        }
      },
    });
  };
 //复制
 const copyOrder = (record: any[]) => {
    if(!record.length){ 
      message.error("请选择工单进行复制操作");
      return
    }
    dispatch({
      type: 'workorder/copyOrder',
      payload: record,
      callback: (response: any) => {
        if (response.status === 200) {
          message.success('操作成功');
          orderList.splice(0, orderList.length);
          setOrderList([])
          handleSearch(searchParam);
        }
      },
    });
  };
 //完成
 const completeOrder = (record: any[]) => {
    if(!record.length){ 
      message.error("请选择工单进行完成操作");
      return
    }
    dispatch({
      type: 'workorder/completeOrder',
      payload: record,
      callback: (response: any) => {
        if (response.status === 200) {
          message.success('操作成功');
          orderList.splice(0, orderList.length);
          setOrderList([])
          handleSearch(searchParam);
        }
      },
    });
  };
  //完成、取消
  const updateState = (record: WorkorderItem, type: Number) => {
    dispatch({
      type: 'workorder/updateState',
      payload: {id: record.id, state: type},
      callback: (response: any) => {
        if (response.status === 200) {
          message.success('操作成功');
          orderList.splice(0, orderList.length);
          setOrderList([])
          handleSearch(searchParam);
        }
      },
    });
  };

  const columns: ColumnProps<WorkorderItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    }, 
    {
      title: '工单名称',
      dataIndex: 'orderName',
    }, 
    {
      title: '设备名称',
      dataIndex: 'deviceName',
    },
    {
      title: '大样号',
      dataIndex: 'imgId',
      align: 'center'
    },
    {
      title: '工单图片',
      width: '150px',
      dataIndex: 'imgUrl',
      render: text =>
      <img
        // style={{height: 70, width: 70}}
        height="80"
        src={text}
      />
    },
    {
      title: '钢筋直径',
      dataIndex: 'barDiamGd',
      align: 'center'
    },
    {
      title: '重量',
      dataIndex: 'weightGd',
      align: 'center'
    },
    {
      title: '已完成数量',
      dataIndex: 'finishNum',
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '状态',
      dataIndex: 'state',
      align: 'center',
      render: text =>
        text === 0 ? <Tag color="#696969">待下发</Tag> : (text === 1 ? <Tag color="#87d068">已下发</Tag> :(text === 2 ? <Tag color="#f50">执行中</Tag> :(text === 3 ? <Tag color="#87d068">已完成</Tag> : <Tag color="#696969">已取消</Tag>))),
    },
    // {
    //   title: '描述',
    //   dataIndex: 'description',
    // },
    {
      title: '操作',
      width: '180px',
      align: 'center',
      fixed: 'right',
      render: (text, record) => (
        <Fragment>
          {record.state === 0 ? 
            <Fragment>
              <a onClick={() => edit(record)}>修改</a>
              <Divider type="vertical" />
              {/* <Popconfirm title="确认下发工单？" onConfirm={() => sendOrder([record.id])}> */}
                <a  onClick={() => showModal([record.id])}>下发</a>
              {/* </Popconfirm> */}
              <Divider type="vertical" />
              <Popconfirm title="确认取消工单？" onConfirm={() => updateState(record, 4)}>
                <a>取消</a>
              </Popconfirm>
            </Fragment>: ''}
          {record.state === 1 ? 
            <Fragment>
              <a onClick={() => edit(record)}>查看</a>
              <Divider type="vertical" />
              <Popconfirm title="确认完成工单？" onConfirm={() => updateState(record, 3)}>
                <a>完成</a>
              </Popconfirm>
            </Fragment>:''}
          {record.state === 2 ? 
            <Fragment>
              <a onClick={() => edit(record)}>查看</a>
              <Divider type="vertical" />
              <Popconfirm title="确认完成工单？" onConfirm={() => updateState(record, 3)}>
                <a>完成</a>
              </Popconfirm>
            </Fragment>:''}
            {record.state === 3 ? 
            <Fragment>
              <a onClick={() => edit(record)}>查看</a>
            </Fragment>:''}
            {record.state === 4 ? 
            <Fragment>
              <a onClick={() => edit(record)}>查看</a>
            </Fragment>:''} 
        </Fragment>
      ),
    },
  ];
  const timeId = () => {
        // setInterval( async() =>{
        //   console.log('dfghjkjkhghjkghj')
        //   handleSearch({
        //     pageIndex: parseInt(localStorage.getItem('pageIndex') || 0),
        //     pageSize: parseInt(localStorage.getItem('pageSize') || 0),
        //     searchParam,
        //     sorts: {},
        //   });
        // })
        setTimeout( ()=>{
          handleSearch({
            pageIndex: parseInt(localStorage.getItem('pageIndex') || 0),
            pageSize: parseInt(localStorage.getItem('pageSize') || 10),
            searchParam,
            sorts: {},
          });
          timeId()
        },15000)
  }

  useEffect(() => {
    localStorage.setItem('pageIndex', '0')
    localStorage.setItem('pageSize', '10')
    handleSearch(searchParam);
    timeId()
    // handleSearch(searchParam);
    // handleSearch(searchParam);
    //获取设备下拉框
    apis.workorder.instanceNopaging({}).then(res => {
      if (res.status === 200) {
        setInstanceList(res.result);
      }
    })
  }, []);

  const saveOrUpdate = (item: WorkorderItem) => {
    setSaveVisible(false);
    orderList.splice(0, orderList.length);
    setOrderList([])
    handleSearch(searchParam);
  };

  const onTableChange = (
    pagination: PaginationConfig,
    filters: any,
    sorter: SorterResult<WorkorderItem>,
  ) => {
    orderList.splice(0, orderList.length);
    setOrderList([])
    localStorage.setItem('pageIndex', (Number(pagination.current) - 1).toString())
    localStorage.setItem('pageSize', pagination.pageSize.toString())
    handleSearch({
      pageIndex: Number(pagination.current) - 1,
      pageSize: pagination.pageSize,
      searchParam,
      sorts: sorter,
    });
    
  };
  //处理搜索中的时间
  const onChange = (params : any) =>{
    if(params){
      if(params?.time){
        params['startTime'] = params.time[0].format('YYYY-MM-DD')
        params['endTime'] = params.time[1].format('YYYY-MM-DD')
        delete params.time
      }
      debugger
      if(params?.state){
        params.state = params?.state
      }
      params['pageSize']= 10
      params['pageIndex']= 0
      localStorage.setItem('pageIndex', '0')
      localStorage.setItem('pageSize', '10')
      setSearchParam(params);
      orderList.splice(0, orderList.length);
      setOrderList([])
      handleSearch(params);
    }else{
      const param = {}
      param['pageSize']= 10
      param['pageIndex']= 0
      setSearchParam(param);
      orderList.splice(0, orderList.length);
      setOrderList([])
      handleSearch(param);
    }
  }

  return (
    <PageHeaderWrapper title="工单管理">
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>

            <SearchForm
              formItems={[
                {
                  label: '设备',
                  key: 'deviceId',
                  type: 'list',
                  props: {
                    data: instanceList,
                    mode: 'instance',
                  }
                },
                {
                  label: '状态',
                  key: 'state',
                  type: 'list',
                  props: {
                    data: stateList,
                    mode: 'state',
                  }
                },
                {
                  label: '开始时间',
                  key: 'time',
                  type: 'dateTimeRangeDay',
                  props: {
                    format: "YYYY-MM-DD",
                    placeholder: ['开始时间', '结束时间'],
                  }
                },
                // {
                //   label: '协议名称',
                //   key: 'name$LIKE',
                //   type: 'string'
                // }
              ]}
              search={(params: any) => {
                // setSearchParam(params);
                onChange(params);
              }}
            />
          </div>
          <div className={styles.tableListOperator}>
            <Button
              icon="plus"
              type="primary"
              onClick={() => {
                setCurrent({});
                setSaveVisible(true);
              }}
            >
              新建
            </Button>
            <Divider type="vertical" />
            <Button type="default" onClick={() => {
              showModal(orderList);
            }}>
              批量下发工单
            </Button>
            <Divider type="vertical" />
            <Button type="default" onClick={() => {
              copyOrder(orderList);
            }}>
              批量复制工单
            </Button>
            <Divider type="vertical" />
            <Button type="default" onClick={() => {
              completeOrder(orderList);
            }}>
              批量完成工单
            </Button>
          </div>
          <div className={styles.StandardTable}>
            <Table
              loading={props.loading}
              dataSource={(result || {}).data}
              columns={columns}
              rowKey='id'
              onChange={onTableChange}
              rowSelection={{
                type: 'checkbox',
                ...rowSelection,
              }}
              scroll={{ x: 1300 }}
              pagination={{
                current: result.pageIndex + 1,
                total: result.total,
                pageSize: result.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: (total: number) => (
                  `共 ${total} 条记录 第  ${result.pageIndex + 1
                  }/${Math.ceil(result.total / result.pageSize)
                  }页`
                ),
              }}
            />
          </div>
        </div>
      </Card>
      {saveVisible && (
        <Save
          data={current}
          close={() => {
            setSaveVisible(false);
          }}
          save={(data: WorkorderItem) => {
            saveOrUpdate(data);
          }}
        />
      )}
      <Modal
        title="是否全量覆盖"
        visible={modelVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Switch checked={issue} onChange={onChangeSwitch} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ workorder, loading }: ConnectState) => ({
  workorder,
  loading: loading.models.workorder,
}))(WorkorderList);
